package cn.wky.cale;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;

import cn.wky.cale.calculate.Calculator;
import cn.wky.cale.key.board.NumKeyBoard;

public class MainActivity extends AppCompatActivity {

    private StringBuilder exprStr = new StringBuilder();
    private TextView exprText;
    private TextView resultText;
    private Calculator calculator;
    private boolean status = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        exprText = findViewById(R.id.expression_text);
        exprText.setMovementMethod(ScrollingMovementMethod.getInstance());
        resultText = findViewById(R.id.result_text);
        calculator = new Calculator(this);
        new NumKeyBoard(this).setDown(new NumKeyBoard.KeyBoardDown() {
            @Override
            public void onDown(int keyCode) {
                if (status) {
                    exprStr.delete(0, exprStr.length());
                    status = false;
                }
                if (0 <= keyCode && keyCode <= 9) {
                    exprStr.append(keyCode);
                } else if (keyCode == 10) {
                    exprStr.append('.');
                } else if (keyCode == 11) {
                    exprStr.append('+');
                } else if (keyCode == 12) {
                    exprStr.append('-');
                } else if (keyCode == 13) {
                    exprStr.append('*');
                } else if (keyCode == 14) {
                    exprStr.append('/');
                } else if (keyCode == -1 && exprStr.length() > 0) {
                    exprStr.deleteCharAt(exprStr.length() - 1);
                }
                update();
            }
        });
    }

    private void update() {
        exprText.setText(exprStr.toString());
    }

    public void calculate(View v) {
        resultText.setText(calculator.eval(exprStr.toString()));
        exprStr.delete(0, exprStr.length());
        //exprText.setText("");
        status = true;
    }
}